package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

type job struct {
	sz int64
}

type result struct {
	job    *job
	cx     int
	result int64
}

var jobChan = make(chan *job, 100)
var resultChan = make(chan *result, 100)
var wg sync.WaitGroup

func main() {

	wg.Add(1)
	go zhoulin(jobChan)
	wg.Add(4)
	for i := 0; i < 4; i++ {
		go baodelu(i, jobChan, resultChan)
	}
	go func() {
		for result := range resultChan {
			fmt.Printf("cx:%d value:%d sum:%d \n", result.cx, result.job.sz, result.result)
		}
	}()
	wg.Wait()
	close(resultChan) //baodelu函数有四个协程，所以只有等这四个协程发送完毕，并退出，才可以关闭resultChan

}

func zhoulin(jobChan chan<- *job) {
	defer wg.Done()
	for i := 0; i < 10; i++ {
		x := rand.Int63()
		newJob := &job{
			sz: x,
		}
		jobChan <- newJob
		time.Sleep(time.Millisecond * 500)
	}
	close(jobChan) //在这里close 是因为jobChan 的数据已经发送完毕

}

func baodelu(i int, jobChan <-chan *job, resultChan chan<- *result) {
	defer wg.Done()
	for job := range jobChan {
		sum := int64(0)
		n := job.sz
		for n > 0 {
			sum += n % 10
			n = n / 10
		}

		newResult := &result{
			job:    job,
			cx:     i,
			result: sum,
		}
		resultChan <- newResult
	}

}
